//config
var C = {
	postUrl: '/pk/pk',
	dataUrl:'/pk/data',
	winUrl:'/pk/prizeChoosen',
	roundCount: 35,
	roundTime: 10, //单位秒
	preloadCount: 4, //预加载数量

	pageSize: {
		x : $(window).width(),
		y : $(window).height()
	},

	headCanvas : Raphael('headCanvas',$('#headCanvas').width(),$('#headCanvas').height()),
	roundEls : [],
	roundPointDis :100 //Round点间距
};
var S = {
	curRound: 1,
	data: itemJson, //数据
	picTpl: template($('#img_tpl').html()),
	config: C
};
S._makeLabel = function(canvas, x, y, text){
	//TODO 直接使用jQuery插件实现, 不用Raphael.
	return canvas.text(x,y,text).attr({'font-size':'16px'});
};
S.initRoundEls = function(){
	var r = C.headCanvas,
		ox = 100, oy = 20,
		dx = (C.pageSize.x - ox*2) / C.roundCount ;
	C.roundPointDis = dx;
	r.rect(ox, oy-1, dx*(C.roundCount-1),2).attr({fill:'#DDD',stroke:'none'});
	for(var i=1; i<= C.roundCount; ++i){
		var x = ox + dx*(i-1), y = oy,
			line = r.rect(x, y-1, 2, 2).attr({stroke:'none',fill:'#666','fill-opacity':0.5}).hide(),
			point = r.circle(x, y, 5).attr({fill:'#999', stroke:'#666','stroke-width':5}),
			label = S._makeLabel(r, x, y+20, '' + i).hide();


		C.roundEls[i] = ({point:point,line:line, label:label});
	}
	/*
	r.circle(100,10,10).attr({fill:'#666', stroke:'#333','stroke-width':5}).animate({stroke:'#33ee33','stroke-width':'8','stroke-opacity':0.7,cx:120,cy:10}, 2000)
	r.circle(200,10,10).attr({fill:'#666', stroke:'#333','stroke-width':5})
	r.text(50,50,'ha大爷的').attr({'font-size':'16px'})
	r.rect(100,10,2,2).attr({'fill-opacity':0.8}).animate({width:100},10000)
	*/
};
S.drawRoundEls = function(n){
	var els = C.roundEls[n];
	els.line.show().animate({width:C.roundPointDis}, C.roundTime*1000);
	els.point.animate({stroke:'#333333','stroke-width':'5','stroke-opacity':0.7},2000);
	els.label.show();
};
S.showRoundResult = function(n, win){
	var els = C.roundEls[n];
	var color = win ? '#33ee33' : '#ee3333';
	els.point.animate({stroke:color,'stroke-width':'8', 'stroke-opacity':0.7}, 2000);
};

S.drawRoundPics = function(n){
	var group = S.data[n];
	var htmlStr = '';
	var center = C.pageSize.x / 2,
		spaceEdge = C.pageSize.x / 15,
		spaceBetween = spaceEdge,
		width = center - (spaceEdge + spaceBetween/2);

	for(var i=0; i < group.length; ++i){
		var pic = group[i];
		var tplData = {
			width: width - 20, //20为相框宽度
			left: (width + spaceBetween) *i + spaceEdge,
			pic_show_url: pic.pic_show_url,
			id: pic.id,
			group: n,
			colorIndex: n % 10 + 1
		}
		htmlStr += S.picTpl(tplData);
	}
	
	$('#pk_main').fadeOut(function(){
		$('#pk_main').html(htmlStr);
	}).fadeIn();
};
S.initDataPk = function (){
	$('[data-pk]').live('click', function(){
		var group = $(this).attr('data-group'),
			winner = $(this).attr('data-pk'),
			loser;
		//现在仅抽出来一个loser,倒霉的.(仅适用于一组两个的场景)
		for (var i = 0; i < S.data[group].length; i++) {
			if(S.data[group][i].id != winner){
				loser = S.data[group][i].id;
			}
		};
		
		$.post(C.postUrl,{
			w: winner,
			l: loser,
			token: token
		}, function(data){
			S.handleRoundResult(data);
		});
	});
};

S.handleRoundResult = function(data){
	try{
		data = eval('(' + data + ')');
	} catch(err){
		data = {rate:50};
	}

	//0. 处理没花的情况.
	//1. 如果错了, 结束本局, 显示错过奖品和重新开始界面.
	//2. 如果对了且有奖品, 展示奖品, 询问是否继续.
	//  2.1 如果选择结束,领奖,展示领奖动画, 显示重新开始界面.
	//  2.2 如果选择继续,则继续.
	//3. 如果对了无奖品, 则继续.
	//TODO: 美化, 奖品逻辑
	if(data.error == 'NoMoney'){
		alert('No Flowers.');
		return;
	}
	
	if(! data.win){ //失败
		if(confirm('功亏一篑, 您已经连续选对了' + (S.curRound -1) +'次, 是否重新开始?') ){
			window.location.reload();
		} else {
			//TODO
		}
		return;
	} else {
		if(data.prize && data.prize.length){
			if(!confirm('恭喜你,赢得了: ' + data.prize[0].name + ',是否继续冲击更高奖?')){
				S.winPrize(data.prize[0].id);
				return;
			}
		}
		EC.fire('round.success', {round:S.curRound});
		//S.showRoundResult(S.curRound, 1);
		S.nextRound();
	}

};
S.winPrize = function(prizeId){
	$.getJSON(C.winUrl, {prizeId:prizeId}, function(data){
		if(data.success){
			if( confirm('领奖成功, 再玩一局?') ) {
				window.location.reload();
			}
		}
	});
	//TODO 
	//1. 发送接受奖品请求
	//2. 领奖成功后提示是否重新开始
};
//预加载图片,以及数据
S.preload = function (loadNum){
	loadNum = loadNum || C.preloadCount; //默认提前加载4组
	var cache = S.preload._cache = S.preload._cache || {};

	if(S.curRound + loadNum >= S.data.length){
		$.getJSON(C.dataUrl, function(data){
			S.data = S.data.concat(data);
			//itemJson= itemJson.concat(data);
			S.preload();
		});
		return;
	}
	for(var i=0; i<loadNum; ++i){
		var idx = S.curRound + 1 + i;
		if(idx < S.data.length){
			var group = S.data[idx];
			for(var k=0; k < group.length; ++k){
				var o = group[k];
				if(! cache[o.id]){
					var img = new Image();
					img.src = o.pic_show_url;
					cache[o.id] = img;
					//log('preload:'+ o.id + " url:" +o.pic_show_url);	
				}
			}
		}
	}
};


S.startRound = function(n){
	//绘出图片
	S.drawRoundPics(n);
	//绘出其他元素
	//S.drawRoundEls(n);
	//预加载
	S.preload();
};

S.nextRound = function(){
	S.startRound(++S.curRound);
};

S.initSize = function(x, y){

}




//初始化函数
$(function(){
	//S.initRoundEls();
	S.initDataPk();
	S.startRound(1);
	//S.drawRoundEls(1);
});

